package com.zenus.thread;

import java.util.concurrent.ExecutorService;

/**
 * zeus ThreadPool Executors
 */
public class ZeusExecutors {
    private static int MIN_CORE_SIZE = 4;
    private static int WAIT_QUEUE_SIZE = 20;
    private static int KEEP_ALIVE_SECONDS = 60;

    static {
        if (Runtime.getRuntime().availableProcessors() <= MIN_CORE_SIZE) {
            MIN_CORE_SIZE = Runtime.getRuntime().availableProcessors();
        }
    }

    /**
     * 获取固定线程数据
     *
     * @param threadNamePrefix 线程前缀
     * @param corePoolSize     核心线程数
     * @param maxPoolSize      最大线程数
     * @param queueCapacity    等待队列
     * @param keepAliveSeconds 线程保存时间
     * @return
     */
    public static ExecutorService newFixedThreadPool(String threadNamePrefix, int corePoolSize, int maxPoolSize, int queueCapacity, int keepAliveSeconds) {
        ZeusThreadPool zeusThreadPool = new ZeusThreadPool(threadNamePrefix, corePoolSize, maxPoolSize, queueCapacity, keepAliveSeconds);
        return zeusThreadPool.getExecutorService();
    }

    /**
     * 获取默认的线程池,最小线程数为4 ,最大为cpu核心数,等待队列20 ,线程保存时间为60秒
     *
     * @param threadNamePrefix
     * @return
     */
    public static ExecutorService newDefaultFixedThreadPool(String threadNamePrefix) {
        int cpuSize = Runtime.getRuntime().availableProcessors();
        ZeusThreadPool zeusThreadPool = new ZeusThreadPool(threadNamePrefix, MIN_CORE_SIZE, cpuSize, WAIT_QUEUE_SIZE, KEEP_ALIVE_SECONDS);
        return zeusThreadPool.getExecutorService();
    }

    public static ExecutorService newCumsterWaitQueueSizeThreadPool(String threadNamePrefix, int waitSize) {
        if (waitSize < 0) { //如果没有指定等等队列大小,使用默认配置
            return newDefaultFixedThreadPool(threadNamePrefix);
        }
        int cpuSize = Runtime.getRuntime().availableProcessors();
        ZeusThreadPool zeusThreadPool = new ZeusThreadPool(threadNamePrefix, MIN_CORE_SIZE, cpuSize, waitSize, KEEP_ALIVE_SECONDS);
        return zeusThreadPool.getExecutorService();
    }

    /**
     * 获取超频线程池
     * 最小线程数为4 ,最大为cpu核心数 * multiple,等待队列20 ,线程保存时间为60秒
     *
     * @param threadNamePrefix 线程前缀
     * @param multiple         超频的倍数
     * @return
     */
    public static ExecutorService newHighFrequencyThreadPool(String threadNamePrefix, int multiple) {
        if (multiple <= 0) {
            multiple = 1;
        }
        if (multiple > 3) {
            multiple = 3;
        }
        int cpuSize = Runtime.getRuntime().availableProcessors() * multiple;
        ZeusThreadPool zeusThreadPool = new ZeusThreadPool(threadNamePrefix, MIN_CORE_SIZE, cpuSize, WAIT_QUEUE_SIZE, KEEP_ALIVE_SECONDS);
        return zeusThreadPool.getExecutorService();
    }
}
